package simulatore;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import random.Random;

public class Simulatore_UM1FCFS extends SimulatoreStazioneSingola {
	
	protected List<Event> eventList;
	protected List<Event> availList;
	
	protected Random random;
	protected double uniform_lower;
	protected double uniform_upper;
	protected double mu;
	
	boolean debug = false;
	
	/*
	 * 	protected List<Event> eventList;
	 *	protected List<Event> availList;
	 * 
	 */
	
	public Simulatore_UM1FCFS(double uniform_lower, double uniform_upper, double mu, double start_time, double end_time, String seed) {
		
		super(start_time, "SINGLERUN");
				
		this.uniform_lower = uniform_lower;
		this.uniform_upper = uniform_upper;
		this.mu = mu;
		
		eventList = new LinkedList<Event>();
		availList = new LinkedList<Event>();
				
		random = new Random();
		random.initialize(seed);		
		
	}
	
	public double ottieniIntervalloTraArriviSuccessivi() {
		
		double temp = random.nextUniformAb(uniform_lower, uniform_upper);
		if(debug)  System.out.println("Intervallo tra arrivi: " + temp);
		
		return temp;
		
	}
	public double ottieniTempoDiServizio() {
		
		double temp = random.nextNegExp(mu);
		if(debug)  System.out.println("Tempo di servizio:" + temp);
		
		return temp;
	}
	
	public Event ottieniPrimoEventoSchedulato() {
		Event e = eventList.remove(0);
		return e;		
	}
	
	public void aggiuntiEventoAvailList(Event e) {
		availList.add(e);
		
	}
	
	// Disciplina di coda: First Come, First Served
	public void schedula(String type, double time, double arrTime) {
		
		Event e;
		
		if(availList.isEmpty()) {
			e = new Event(type, arrTime);
		} else {
			e = availList.remove(0);
			e.setEventType(type);
			e.setOccurTime(arrTime);
		}
		
		Iterator<Event> it = eventList.iterator();
		Event temp;
		int i = 0;
		boolean found = false;
		while(it.hasNext() && !found) {
			temp = it.next();
			if(e.getOccurTime() < temp.getOccurTime()) {
				eventList.add(i,e);
				found = true;
			}
			i++;			
		}
		if(!found)		eventList.add(e);
	}

	

}
